#include "Connection.h"
#include <iostream>
#include <stdio.h> //perror
#include <stdlib.h> //exit
#include <unistd.h> //close
#include <errno.h>
 

 CConnection::CConnection()
{
     m_worker_connections = 10000;
     m_nTotalConnections =0 ;						//连接池总连接数

     m_nFreeConnections =0 ;							//连接池空闲连接数

}

 CConnection::~CConnection()
{

}
void CConnection::InitConnections()
{
	std::lock_guard <std::mutex> lock(m_MutexConn);
	sClient *p_Conn;

    for (int i = 0; i < m_worker_connections; ++i) 
    {
        p_Conn = new  sClient;   

        p_Conn->Init();

        m_ConnectionList.push_back(p_Conn);         //所有链接

        m_FreeConnectionList.push_back(p_Conn); //空闲连接会放在这个list

    }

    m_nFreeConnections = m_nTotalConnections = m_ConnectionList.size();

}
void CConnection::ClearConnections()
{
	std::lock_guard <std::mutex> lock(m_MutexConn);

	sClient *p_Conn;

    while (!m_ConnectionList.empty())
    {
        p_Conn = m_ConnectionList.front();

        m_ConnectionList.pop_front();

        //p_Conn->~ngx_connection_t();

        delete p_Conn;
    }

}		
sClient* CConnection::GetConnection(int isock)
{
	std::lock_guard <std::mutex> lock(m_MutexConn);
	
    if (!m_FreeConnectionList.empty())
    {
        sClient *p_Conn = m_FreeConnectionList.front(); 		  
        m_FreeConnectionList.pop_front();
        
        p_Conn->Init();
        p_Conn->GetOneToUse();

        --m_nFreeConnections;
        p_Conn->fd = isock;
        return p_Conn;
    }   
    sClient *p_Conn = new (std::nothrow)  sClient;
    if (p_Conn == nullptr)
    {
        return  p_Conn;
    }
    p_Conn->Init();
    p_Conn->GetOneToUse();

    m_ConnectionList.push_back(p_Conn); //入到总表中来，但不能入到空闲表中来，因为凡是调这个函数的，肯定是要用这个连接的
    ++m_nTotalConnections;
    p_Conn->fd = isock;
    return p_Conn;
}
void CConnection::FreeConnection(sClient*p_Conn)
{
	std::lock_guard <std::mutex> lock(m_MutexConn);
   if (p_Conn->b_In == true)
    {
        return;
    }

    p_Conn->PutOneToFree();

    m_FreeConnectionList.push_back(p_Conn);

	++m_nFreeConnections;

	printf("FreeConnection():m_nFreeConnections Size:%d m_nTotalConnections Size:%d  \n",(int)m_nFreeConnections,(int)m_nTotalConnections);  
	return;
}

